import { Component, ReactNode } from "react";
import { ScrollView, View, Text } from "@tarojs/components";
import { Button, Image } from "@tarojs/components";
import { AtSearchBar, AtList, AtListItem, AtButton } from "taro-ui";
import i1 from "./images/i1.png";
import Taro from "@tarojs/taro";
import "./index.scss";
import Req from "../../utils/request";
import { delay } from "../../utils/kit";
import { getInfo } from "../../utils/auth";

export default class ProjectManagement extends Component {
  state = {
    value: "",
    currentPage: 1,
    loading: false,
    hasMore: true,
    refreshing: false,
    total: 0,
    list: [],
  };
  get isProjectAdmin() {
    const user_info = getInfo();
    const { roles = [] } = user_info;
    if (roles.length) {
      let hasProject = roles.map((e) => e.roleKey).includes("company_admin");
      return !hasProject;
    }
    return false;
  }
  onChange = (val: string) => {
    this.setState({
      value: val,
    });
  };
  onClear = () => {
    this.setState(
      {
        value: "",
      },
      () => {
        this.onActionClick();
      }
    );
  };
  onActionClick = () => {
    console.log("开始搜索", this.state.value);
    this.setState(
      {
        list: [],
        total: 0,
        hasMore: true,
      },
      () => {
        this.loadData();
      }
    );
  };
  handleAdd = () => {
    Taro.navigateTo({
      url: "/pages/project-form/index",
    });
  };
  goToDetail = (id: string) => {
    Taro.navigateTo({
      url: `/packages/detail/pages/index?id=${id}`,
    });
  };
  componentDidMount(): void {
    this.loadData();
  }
  componentDidUpdate() {
    Taro.eventCenter.on("refreshData", this._onBackRefresh);
  }
  _onBackRefresh = (v) => {
    if (v.force) {
      this._refreshData();
    }
  };
  _refreshData = () => {
    this.setState(
      {
        value: "",
        currentPage: 1,
        loading: false,
        hasMore: true,
        total: 0,
        list: [],
      },
      () => {
        this.loadData();
      }
    );
  };
  componentWillUnmount() {
    Taro.eventCenter.off("refreshData");
  }
  loadData = () => {
    const { currentPage, list, value } = this.state;
    this.setState(
      {
        loading: true,
      },
      () => {
        Req.get(
          "/project/list",
          {
            userId: getInfo()?.userId,
            title: this.state.value,
            pageNum: currentPage,
            pageSize: 10,
          },
          {
            loading: false,
          }
        )
          .then((r) => {
            if (r.total - list.length === 0 || r.rows.length < 10) {
              console.log(currentPage, "currentPage");
              this.setState({
                hasMore: false,
              });
            }
            this.setState({
              total: r.total,
              list: list.concat([...r.rows] as any),
              currentPage: currentPage + 1,
              loading: false,
              refreshing: false,
            });
          })
          .catch((e) => {
            this.setState({
              refreshing: false,
              loading: false,
            });
          });
      }
    );
  };
  onScrollDetchEnd = () => {
    const { loading, hasMore, currentPage } = this.state;
    if (loading) return;
    if (hasMore) {
      console.log("请求数据：", currentPage);
      this.loadData();
    } else {
      this.setState({
        loading: false,
      });
    }
  };
  formatDate = (date: Date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    const seconds = String(date.getSeconds()).padStart(2, "0");

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };
  onRefresh = () => {
    this.setState(
      {
        refreshing: true,
      },
      () => {
        delay(600).then(() => {
          this._refreshData();
        });
      }
    );
  };
  render(): ReactNode {
    console.log(this.isProjectAdmin);
    return (
      <View className="pm-container app-container">
        <View className="top-header">
          <AtSearchBar
            className="em-search-bar"
            value={this.state.value}
            onChange={this.onChange}
            onClear={this.onClear}
            onActionClick={this.onActionClick}
          />
          {!this.isProjectAdmin && (
            <Button onClick={this.handleAdd} className="text-button">
              <Image className="icon-1" src={i1} />
              新增
            </Button>
          )}
        </View>
        <ScrollView
          lowerThreshold={80}
          refresherTriggered={this.state.refreshing}
          enhanced
          showScrollbar={false}
          refresherEnabled
          onRefresherRefresh={this.onRefresh}
          onScrollToLower={this.onScrollDetchEnd}
          scrollY
          className="pm-list"
        >
          <AtList>
            {this.state.list.map((item: any, index) => (
              <AtListItem
                onClick={() => {
                  this.goToDetail(item.id);
                }}
                className="no-arrow-space"
                key={index}
                title={
                  <View className="pm-list-title">
                    {item.areaName && (
                      <Text className="pm-list-tag">{item.areaName}</Text>
                    )}
                    <Text className="pm-list-title-t1 two-line-max-text">
                      {item.companyName}
                    </Text>
                  </View>
                }
                note={
                  <View className="pm-list-note">
                    <View className="p-m-n-left">
                      <Text className="p-m-n-l-info two-line-max-text">
                        {item.title}
                      </Text>
                      <Text className="p-m-n-l-date">
                        {this.formatDate(new Date(item.createTime))}
                      </Text>
                    </View>
                    {item.debt && (
                      <Text className="p-m-n-right">￥{item.debt}</Text>
                    )}
                  </View>
                }
              />
            ))}
          </AtList>
          <View className="em-center-text">
            <Text>{this.state.hasMore ? "加载中..." : "没有更多了"}</Text>
          </View>
        </ScrollView>
      </View>
    );
  }
}
